import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem';
import Test from './Test';
import axios from 'axios';

class TodoList extends Component{
	constructor(props){
		super(props);
		this.state = {
			//当state或者props发生改变的时候，render方法就会重新执行
			inputValue: '',
			list: []
		}
		this.hanleInput = this.hanleInput.bind(this);
		this.hanleChange = this.hanleChange.bind(this);
		this.deItem = this.deItem.bind(this)
	}
	render() {
		console.log('render');
		return (
			<Fragment>
				<div>
					<label htmlFor='FFF'>SHURU</label>
					<input id='FFF' value={this.state.inputValue} onChange={this.hanleChange} />
					<button onClick={this.hanleInput}>提交</button>
				</div>
				<ul>
					{ this.getTo()}
				</ul>
				<Test content={this.state.inputValue} />
			</Fragment>
		)
	}

	componentDidMount() {
		axios.get('api/todo')
		.then((res) => {
			this.setState(() => ({
				list: [...res.data]
			}))
		})
		.catch(() => {alert('error')})
	}

	getTo(){
		return this.state.list.map((item, index) => {
						return (
							<TodoItem 
								key={item}
								content={item}
								index={index}
								deleClick = {this.deItem}
							/>
						)
					})
	}

	hanleChange(e){
		const value = e.target.value;
		this.setState(() => ({
			inputValue: value
		}))
	}

	hanleInput(){
		this.setState((prevState) => ({
			list: [...prevState.list, prevState.inputValue],
			inputValue: ''
		}))
	}

	deItem(index) {

		this.setState((prevState) => {
			const list =[...prevState.list];
			list.splice(index, 1);
			return {
			list: list
			}
		})
	}
}

export default TodoList;